<template>
  <div class="user-center">
    <el-container>
      <el-aside width="200px" class="user-aside">
        <el-menu
          :default-active="activeMenu"
          class="user-menu"
          @select="handleMenuSelect"
          background-color="#f0f6ff"
          text-color="#333"
          active-text-color="#409EFF"
        >
          <el-menu-item index="profile">
            <el-icon><User /></el-icon>
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="houses" v-if="isLandlord">
            <el-icon><House /></el-icon>
            <span>我的房源</span>
          </el-menu-item>
          <el-menu-item index="rentals" v-if="isTenant">
            <el-icon><Document /></el-icon>
            <span>我的租赁</span>
          </el-menu-item>
          <el-menu-item index="news" v-if="isLandlord">
            <el-icon><Bell /></el-icon>
            <span>消息管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <!-- 个人信息 -->
        <el-card v-if="activeMenu === 'profile'" class="user-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" @click="handleEditProfile" round icon="Edit">编辑</el-button>
            </div>
          </template>
          <el-form :model="userInfo" label-width="100px">
            <el-form-item label="用户名">
              <span>{{ userInfo.username }}</span>
            </el-form-item>
            <el-form-item label="手机号码">
              <span>{{ userInfo.phone }}</span>
            </el-form-item>
            <el-form-item label="角色">
              <span>{{ userInfo.role === 'landlord' ? '房东' : '租客' }}</span>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 我的房源（房东） -->
        <div v-if="activeMenu === 'houses' && isLandlord" class="landlord-section">
          <div class="section-header">
            <h3>我的房源</h3>
            <div class="header-actions">
              <el-button type="info" @click="fetchStatistics" size="small" round>
                <el-icon><DataAnalysis /></el-icon>
                统计信息
              </el-button>
            <el-button type="primary" @click="router.push('/house/publish')" round>
              <el-icon><Plus /></el-icon>
              发布新房源
            </el-button>
            </div>
          </div>
          
          <!-- 统计信息卡片 -->
          <div v-if="showStatistics" class="statistics-section">
            <div class="statistics-header">
              <h4>房源统计概览</h4>
              <el-button @click="showStatistics = false" text type="info" size="small">
                收起统计
              </el-button>
            </div>
            <el-row :gutter="16">
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-item">
                    <div class="stat-number">{{ statistics.total_houses }}</div>
                    <div class="stat-label">总房源</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card available">
                  <div class="stat-item">
                    <div class="stat-number">{{ statistics.status_breakdown?.available || 0 }}</div>
                    <div class="stat-label">可租</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card rented">
                  <div class="stat-item">
                    <div class="stat-number">{{ statistics.status_breakdown?.rented || 0 }}</div>
                    <div class="stat-label">已租</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-item">
                    <div class="stat-number">{{ statistics.occupancy_rate || 0 }}%</div>
                    <div class="stat-label">入住率</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <!-- 状态说明 -->
            <div class="status-guide">
              <h5>状态说明：</h5>
              <div class="guide-items">
                <div class="guide-item">
                  <el-tag type="success" size="small">可租</el-tag>
                  <span>房源可以对外出租</span>
                </div>
                <div class="guide-item">
                  <el-tag type="danger" size="small">已租</el-tag>
                  <span>房源已被租出</span>
                </div>
                <div class="guide-item">
                  <el-tag type="warning" size="small">维修中</el-tag>
                  <span>房源正在维修，暂时不可租</span>
                </div>
                <div class="guide-item">
                  <el-tag type="info" size="small">不可用</el-tag>
                  <span>房源暂时下架或不可用</span>
                </div>
              </div>
            </div>
          </div>
          
          <el-table :data="landlordHouses" style="width: 100%" v-loading="loading">
            <el-table-column prop="title" label="标题" min-width="200" />
            <el-table-column prop="price" label="价格" width="120">
              <template #default="{ row }">
                ¥{{ row.price }}/月
              </template>
            </el-table-column>
            <el-table-column prop="area" label="面积" width="120">
              <template #default="{ row }">
                {{ row.area }}㎡
              </template>
            </el-table-column>
            <el-table-column prop="type" label="户型" width="120" />
            <el-table-column prop="status" label="状态" width="150">
              <template #default="{ row }">
                <el-select 
                  v-model="row.status" 
                  @change="handleStatusChange(row.id, row.status)"
                  size="small"
                  style="width: 100%"
                >
                  <el-option 
                    v-for="status in statusOptions" 
                    :key="status.value"
                    :label="status.label" 
                    :value="status.value"
                  >
                    <el-tag :type="status.type" size="small">{{ status.label }}</el-tag>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="发布时间" width="180">
              <template #default="{ row }">
                {{ new Date(row.created_at).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-button type="primary" size="small" @click="handleEditHouse(row.id)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteHouse(row.id)">
                    删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 我的租赁（租客） -->
        <el-card v-if="activeMenu === 'rentals' && isTenant" class="user-card">
          <template #header>
            <div class="card-header">
              <span>我的租赁</span>
            </div>
          </template>
          <el-table :data="rentals" style="width: 100%" stripe border>
            <el-table-column prop="title" label="房源标题" />
            <el-table-column prop="price" label="月租金" />
            <el-table-column prop="startDate" label="开始日期" />
            <el-table-column prop="endDate" label="结束日期" />
            <el-table-column prop="status" label="状态" />
          </el-table>
        </el-card>
        <!-- 消息管理（房东） -->
        <el-card v-if="activeMenu === 'news' && isLandlord" class="user-card">
          <template #header>
            <div class="card-header">
              <span>消息管理</span>
              <el-button type="primary" @click="handleAddNews" round icon="Plus">发布消息</el-button>
            </div>
          </template>
          <el-table :data="news" style="width: 100%" stripe border>
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="content" label="内容" />
            <el-table-column prop="createTime" label="发布时间" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleEditNews(scope.row)" icon="Edit" round>编辑</el-button>
                <el-button type="danger" size="small" @click="handleDeleteNews(scope.row)" icon="Delete" round>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { User, House, Document, Bell, Edit, Plus, Delete, DataAnalysis } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { houseApi } from '../api'

const activeMenu = ref('profile')
const userInfo = ref({
  username: '张三',
  phone: '13800138000',
  role: localStorage.getItem('userRole') || 'tenant'
})
const isLandlord = computed(() => userInfo.value.role === 'landlord')
const isTenant = computed(() => userInfo.value.role === 'tenant')
const router = useRouter()
const landlordHouses = ref([])
const loading = ref(false)
const showStatistics = ref(false)
const statistics = ref({})

// 房源状态选项
const statusOptions = [
  { value: 'available', label: '可租', type: 'success' },
  { value: 'rented', label: '已租', type: 'danger' },
  { value: 'maintenance', label: '维修中', type: 'warning' },
  { value: 'unavailable', label: '不可用', type: 'info' }
]

// 模拟数据
const houses = ref([
  {
    id: 1,
    title: '阳光花园精装两居室',
    price: 3500,
    area: '80㎡',
    status: '已出租'
  }
])
const rentals = ref([
  {
    id: 1,
    title: '市中心豪华三居室',
    price: 6000,
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    status: '租赁中'
  }
])
const news = ref([
  {
    id: 1,
    title: '房屋维修通知',
    content: '本周六将进行水管维修，请各位租户注意',
    createTime: '2024-03-15'
  }
])

// 获取房东的房源列表
const fetchLandlordHouses = async () => {
  loading.value = true
  try {
    const data = await houseApi.getLandlordHouses()
    landlordHouses.value = data
  } catch (error) {
    console.error('获取房源列表失败:', error)
    ElMessage.error('获取房源列表失败')
  } finally {
    loading.value = false
  }
}

// 删除房源
const handleDeleteHouse = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个房源吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await houseApi.deleteHouse(id)
    ElMessage.success('删除成功')
    fetchLandlordHouses() // 重新获取列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 编辑房源
const handleEditHouse = (id) => {
  router.push(`/house/edit/${id}`)
}

// 在组件挂载时获取房源列表
onMounted(() => {
  if (userInfo.value.role === 'landlord') {
    fetchLandlordHouses()
  }
})

const handleMenuSelect = (key) => {
  activeMenu.value = key
}

const handleEditProfile = () => {
  ElMessage.info('个人信息编辑功能开发中')
}

const handleAddNews = () => {
  ElMessage.info('发布消息功能开发中')
}

const handleEditNews = (news) => {
  ElMessage.info('编辑消息功能开发中')
}
const handleDeleteNews = (news) => {
  ElMessage.info('删除消息功能开发中')
}

const fetchStatistics = async () => {
  try {
    const data = await houseApi.getStatistics()
    statistics.value = data
    showStatistics.value = true
  } catch (error) {
    console.error('获取统计信息失败:', error)
    ElMessage.error('获取统计信息失败')
  }
}

const handleStatusChange = async (id, status) => {
  try {
    await houseApi.updateHouseStatus(id, status)
    ElMessage.success('状态更新成功')
    fetchLandlordHouses() // 重新获取列表
  } catch (error) {
    console.error('更新房源状态失败:', error)
    ElMessage.error('更新房源状态失败')
  }
}
</script>

<style scoped>
.user-center {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e3f0ff 100%);
}
.user-aside {
  background: #f0f6ff;
  border-right: 1px solid #e6e6e6;
  min-height: 100vh;
  padding-top: 24px;
}
.user-menu {
  border-right: none;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(64,158,255,0.08);
  background: #f0f6ff;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.user-card {
  margin-bottom: 32px;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(64,158,255,0.08);
  background: #fff;
  animation: fadeInUp 0.5s;
}
.el-main {
  padding: 32px 24px;
}
@keyframes fadeInUp {
  0% { opacity: 0; transform: translateY(40px); }
  100% { opacity: 1; transform: translateY(0); }
}
@media (max-width: 900px) {
  .user-aside { display: none; }
  .el-main { padding: 8px; }
}

.landlord-section {
  margin-top: 24px;
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.statistics-section {
  margin-bottom: 24px;
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.statistics-header h4 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.el-button-group {
  display: flex;
  gap: 8px;
}

.el-button-group .el-button {
  margin-left: 0;
}

.status-guide {
  margin-top: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.guide-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.guide-item {
  display: flex;
  align-items: center;
}

.guide-item .el-tag {
  margin-right: 8px;
}

.guide-item span {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card.available {
  border-left: 4px solid #67c23a;
}

.stat-card.rented {
  border-left: 4px solid #f56c6c;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}
</style> 